package com.example.demo.commons;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

@Component
public class SessionManager {

    private final HttpServletRequest request;

    @Autowired
    public SessionManager(HttpServletRequest request) {
        this.request = request;
    }

    /**
     * 根据请求地址获取appCode。请求地址格式为：http://domain/{appCode}/{requestUri}
     *
     * @return
     * @throws ServletException
     */
    public String getAppCode() {
        final var servletPath = request.getServletPath();
        final var pathParts = servletPath.split("/", 3);
        if (pathParts.length < 3) {
            throw new IllegalArgumentException("请求路径未包含appCode：" + servletPath);
        }
        return pathParts[1];
    }

    public SessionObject getSessionObject() {
        final var appCode = getAppCode();
        final var session = request.getSession(true);
        // 不用的appCode表示不同的公众号，不同的公众号持有不同的会话属性
        if (session.getAttribute(appCode) == null) {
            session.setAttribute(appCode, new SessionObject());
        }
        return (SessionObject) session.getAttribute(appCode);
    }
}
